package cn.usbtg.httpsession.servlet.handler;

import cn.usbtg.httpsession.kit.SessionKit;
import cn.usbtg.httpsession.servlet.BTGHttpServletRequest;
import cn.usbtg.sutil.EmptyUtil;
import com.jfinal.handler.Handler;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 全局拦截器：接管session并自动设置cookie
 */
public class BTGHttpSessionHandler extends Handler {

    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        request = new BTGHttpServletRequest(request);//替换自定义session的request扩展

        //根据是否开启简单单点登录设置默认cookie path
        if (SessionKit.isDisableSimpleSSO()) {
            SessionKit.setSessionCookiePath(request.getContextPath() + "/");
        }

        //自动设置session cookie
        HttpSession session = request.getSession(false);
        if (EmptyUtil.isEmpty(session)) {
            session = SessionKit.getNewSession();
            Cookie sessionCookie = new Cookie(SessionKit.getSessionIdKey(), session.getId());
            sessionCookie.setPath(SessionKit.getSessionCookiePath());
            sessionCookie.setMaxAge(session.getMaxInactiveInterval() / 1000);
            response.addCookie(sessionCookie);
        }

        next.handle(target, request, response, isHandled);
    }
}